<template>
  <div>
    <h2>实验室数据管理</h2>
    
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6">
        <el-input
          v-model="searchQuery"
          placeholder="搜索地块ID"
          clearable
        />
      </el-col>
      <el-col :span="6">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-col>
      <el-col :span="6" style="text-align: right;">
        <el-button type="success" @click="handleExport">导出数据</el-button>
        <el-button type="primary" @click="showUploadDialog = true">导入数据</el-button>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <el-card>
          <template #header>
            <span>实验室检测数据</span>
          </template>
          <el-table :data="tableData" style="width: 100%" v-loading="loading">
            <el-table-column prop="plot_id" label="地块ID" width="100" />
            <el-table-column prop="test_date" label="检测日期" width="120" />
            <el-table-column prop="ph" label="pH值" width="80" />
            <el-table-column prop="soc" label="SOC (%)" width="100" />
            <el-table-column prop="nitrogen" label="全氮 (g/kg)" width="100" />
            <el-table-column prop="phosphorus" label="有效磷 (mg/kg)" width="120" />
            <el-table-column prop="potassium" label="速效钾 (mg/kg)" width="120" />
            <el-table-column prop="texture" label="质地" width="100" />
            <el-table-column prop="tester" label="检测人员" width="100" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button type="text" size="small" @click="handleEdit(row)">编辑</el-button>
                <el-button type="text" size="small" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 上传对话框 -->
    <el-dialog
      v-model="showUploadDialog"
      title="导入实验室数据"
      width="500px"
    >
      <el-upload
        class="upload-demo"
        drag
        action="#"
        :before-upload="beforeUpload"
        :on-success="handleUploadSuccess"
        :file-list="fileList"
        accept=".xlsx,.xls,.csv"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 .xlsx, .xls, .csv 格式文件，文件大小不超过 10MB
          </div>
        </template>
      </el-upload>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="showEditDialog"
      :title="editForm.id ? '编辑数据' : '新增数据'"
      width="600px"
    >
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="地块ID">
          <el-input v-model="editForm.plot_id" />
        </el-form-item>
        <el-form-item label="检测日期">
          <el-date-picker v-model="editForm.test_date" type="date" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="pH值">
              <el-input-number v-model="editForm.ph" :min="0" :max="14" :step="0.1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="SOC (%)">
              <el-input-number v-model="editForm.soc" :min="0" :max="100" :step="0.01" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="全氮 (g/kg)">
              <el-input-number v-model="editForm.nitrogen" :min="0" :step="0.1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效磷 (mg/kg)">
              <el-input-number v-model="editForm.phosphorus" :min="0" :step="0.1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="速效钾 (mg/kg)">
              <el-input-number v-model="editForm.potassium" :min="0" :step="0.1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质地">
              <el-select v-model="editForm.texture">
                <el-option label="砂土" value="砂土" />
                <el-option label="壤土" value="壤土" />
                <el-option label="粘土" value="粘土" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="检测人员">
          <el-input v-model="editForm.tester" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const searchQuery = ref('')
const dateRange = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)
const showUploadDialog = ref(false)
const showEditDialog = ref(false)
const fileList = ref([])

const tableData = ref([
  {
    id: 1,
    plot_id: 'P001',
    test_date: '2024-11-10',
    ph: 6.8,
    soc: 2.41,
    nitrogen: 1.2,
    phosphorus: 12.5,
    potassium: 156.8,
    texture: '壤土',
    tester: '张三'
  },
  {
    id: 2,
    plot_id: 'P002',
    test_date: '2024-11-09',
    ph: 7.1,
    soc: 2.28,
    nitrogen: 1.15,
    phosphorus: 10.8,
    potassium: 142.3,
    texture: '砂壤土',
    tester: '李四'
  }
])

const editForm = ref({
  plot_id: '',
  test_date: '',
  ph: 7.0,
  soc: 2.0,
  nitrogen: 1.0,
  phosphorus: 10.0,
  potassium: 150.0,
  texture: '壤土',
  tester: ''
})

const handleSearch = () => {
  loading.value = true
  // 模拟搜索
  setTimeout(() => {
    loading.value = false
  }, 500)
}

const handleReset = () => {
  searchQuery.value = ''
  dateRange.value = []
  handleSearch()
}

const handleExport = () => {
  // 模拟导出
  const data = tableData.value.map(row => ({
    地块ID: row.plot_id,
    检测日期: row.test_date,
    pH值: row.ph,
    SOC: row.soc,
    全氮: row.nitrogen,
    有效磷: row.phosphorus,
    速效钾: row.potassium,
    质地: row.texture,
    检测人员: row.tester
  }))
  
  const csvContent = "data:text/csv;charset=utf-8," + 
    Object.keys(data[0]).join(",") + "\n" +
    data.map(row => Object.values(row).join(",")).join("\n")
  
  const encodedUri = encodeURI(csvContent)
  const link = document.createElement("a")
  link.setAttribute("href", encodedUri)
  link.setAttribute("download", "实验室数据.csv")
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const handleEdit = (row) => {
  editForm.value = { ...row }
  showEditDialog.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除地块 ${row.plot_id} 的检测数据吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟删除
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  })
}

const handleSave = () => {
  // 模拟保存
  if (editForm.value.id) {
    const index = tableData.value.findIndex(item => item.id === editForm.value.id)
    if (index > -1) {
      tableData.value[index] = { ...editForm.value }
    }
  } else {
    editForm.value.id = Date.now()
    tableData.value.unshift({ ...editForm.value })
  }
  showEditDialog.value = false
  ElMessage.success('保存成功')
}

const beforeUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
  }
  return isLt10M
}

const handleUploadSuccess = () => {
  ElMessage.success('文件上传成功')
  showUploadDialog.value = false
}

const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

onMounted(() => {
  handleSearch()
})
</script>
